<?php

namespace Jin\Laraveltools\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Str;

class Validation
{

    public function handle(Request $request, Closure $next)
    {
        
        $this->todo($request);
        return $next($request);

    }

    protected function todo(Request $request)
    {
        $file = config("j-tools.validation.file");
        if (!file_exists($file)) {
            return;
        }
        
        $content = file_get_contents($file) ?? null;
        if(!$content) {
            return;
        }

        $arr = json_decode($content, true);
        
        $route = $request->route();
        if(!$route) {
            return;
        }
        $action = $route->getAction();
        
        $controller = $action["controller"] ?? "";

        $rules = $arr[$controller] ?? [];
        $ruleArr = [];
        $ruleFunArr =  [];
        foreach ($rules as $r) {
            $name = $r["name"];
            $v = $r["v"];
            if(Str::startsWith($v, '#')) {
                $fun = Str::substr($v, 1);
                
                $ruleFunArr[] = $fun();
            }else{
                $ruleArr[$name] = $v;
            }
            
        }


        $val = Validator::make($request->all(), $ruleArr, config("j-tools.error_message"));
        $val->getMessageBag()->add("haha","vvvsa");
        $val->addFailure("Size","uploaded");
        
        app()["j-errors"] =  $val;



        
    }
}
